﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;

namespace Cemit.PolyServer
{
    /// <summary>
    /// 表示一个Json配置文件
    /// </summary>
    public class JsonConfigs : IConfigs
    {
        readonly IConfigurationRoot m_Configs;
        readonly string m_Path;

        public JsonConfigs(string path)
        {
            if (!File.Exists(GetPath()))
            {
                throw new Exception("文件不存在！请确认文件已启用[复制到输出目录]！" +
                    "文件路径：" + GetPath());
            }
            
            m_Configs = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile(path)
                .Build();

            m_Path = path;

            string GetPath()
                => Path.Combine(Directory.GetCurrentDirectory(), path);
        }

        public string[] GetKeys()
        {
            return m_Configs
                .GetChildren()
                .Select(a => a.Key)
                .ToArray();
        }

        public string GetValue(string jsonPathKey)
        {
            string ret = ProcessJsonVariables(m_Configs[jsonPathKey]);
            if (string.IsNullOrEmpty(ret))
            {
                throw new Exception ($"{m_Path} 中找不到 Key 为 {jsonPathKey} 的项");
            }

            return ret;
        }

        public string[] GetValues(string key)
        {
            List<string> ret = new List<string>();
            foreach (IConfigurationSection item in m_Configs.GetSection(key).GetChildren())
            {
                ret.Add(ProcessJsonVariables(item.Value));
            }
            return ret.ToArray();
        }

        private string ProcessJsonVariables(string jsonValue)
        {
            if (jsonValue.HasAllValues("{{", "}}"))
            {
                return jsonValue.GetLefts("{{")
                    + GetValue(jsonValue.GetMiddles("{{", "}}"))
                    + jsonValue.GetRights("}}");
            }

            return jsonValue;
        }

    }
}
